from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session

from core.config import settings
from core.database import get_db
from core.dependencies import get_redis_service
from db.pydantic.request.voice import VoiceTTSRequest, TalkStatusRequest
from services.voice_service import get_voice_service, VoiceService
from utils.ali_access_token import AccessToken
from utils.result import Result
import io

router = APIRouter()

@router.post("/api/voice/tts")
async def tts(req: VoiceTTSRequest,voice_service:VoiceService = Depends(get_voice_service)):
    """
    tts
    """
    content =  await voice_service.tts_voice(req)
    if not content:
        raise HTTPException(status_code=500, detail="语音合成失败")
    return StreamingResponse(io.BytesIO(content), media_type="audio/mpeg")

@router.post("/api/voice/store/tts")
async def store_tts(req: VoiceTTSRequest,voice_service:VoiceService = Depends(get_voice_service)):
    """
    tts
    """
    content =  await voice_service.tts_voice(req)
    if not content:
        raise HTTPException(status_code=500, detail="存储失败")
    with open(rf"D:\project\tts\{req.file_name}.wav", "wb") as f:
        f.write(content)
    return Result.success(data="ok")

@router.post("/qw/api/voice/status")
async def voice_status(req: TalkStatusRequest,voice_service:VoiceService = Depends(get_voice_service),db: Session = Depends(get_db)):
    """
    tts
    """
    result = await voice_service.store_voice_status(req,db)
    if not result:
        raise HTTPException(status_code=500, detail="存储通话状态失败")
    return Result.success(data=result)

@router.get("/qw/api/voice/status")
async def voice_status(device_phone: str,voice_service:VoiceService = Depends(get_voice_service)):
    """
    获取设备手机号的通话状态
    """
    result = await voice_service.get_voice_status(device_phone)
    return Result.success(data=result)



@router.get("/api/voice/token")
async def get_token():
    """
    获取token
    """
    redis_server = await get_redis_service()
    await redis_server.init_redis()
    token = await redis_server.get_ali_access_token()
    if not token:
        # 获取token，从redis中获取
        token, expire_time = AccessToken.create_token(settings.ALI_ACCESS_KEY_ID, settings.ALI_ACCESS_KEY_SECRET)
        if not token:
            return None
        await redis_server.set_ali_access_token(token, expire_time)
        return {"token": token, "expire_time": expire_time}
    return {"token": token}